const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
//指定上传文件存储路径和存储文件名
var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, 'uploads');
    },
    filename: function(req, file, cb) {
        let oriName = file.originalname;
        cb(
            null,
            Date.now() +
                oriName.substring(oriName.lastIndexOf('.'), oriName.length)
        );
    }
});

const upload = multer({ storage: storage });
const app = express();

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get('/', (req, res) => res.send('Hello World!'));
//查询字符串    req.query
app.get('/find', (req, res) => res.send('find:' + req.query.find));

//sendfile
app.get('/form', (req, res) => res.sendFile(__dirname + '/form.html'));

//路由参数   req.params
app.get('/video/:id', (req, res) => res.send('id is :' + req.params.id));

//post请求处理   使用bodyParser中间件进行处理
app.post('/postForm', urlencodedParser, (req, res) => {
    console.log(req.body);
    res.json(req.body);
});
//post请求处理   使用bodyParser中间件进行处理
app.post('/postJson', jsonParser, (req, res) => {
    console.log(req.body);
    res.json(req.body);
});

//post请求处理文件上传
var cpUpload = upload.fields([
    { name: 'file', maxCount: 3 },
    { name: 'file1', maxCount: 8 }
]);
app.post('/postUpload', cpUpload, (req, res) => {
    res.send({
        upload: 'file'
    });
});

app.listen(3000, () => console.log('Example app listening on port 3000!'));
